package com.micro.user.controller;

import com.micro.user.dto.UserInfoDTO;
import com.micro.user.dto.UserProfileDTO;
import com.micro.user.dto.request.LoginRequest;
import com.micro.user.dto.request.RegisterRequest;
import com.micro.user.dto.response.LoginResponse;
import com.micro.user.entity.User;
import com.micro.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 
 * @author micro
 * @since 1.0.0
 */
@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<User> register(@Valid @RequestBody RegisterRequest request) {
        User user = userService.register(request);
        return ResponseEntity.ok(user);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@Valid @RequestBody LoginRequest request) {
        LoginResponse response = userService.login(request);
        return ResponseEntity.ok(response);
    }

    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<Boolean> checkUsernameAvailable(@RequestParam String username) {
        boolean available = userService.isUsernameAvailable(username);
        return ResponseEntity.ok(available);
    }

    /**
     * 根据用户名查询用户信息
     */
    @GetMapping("")
    public ResponseEntity<User> getUserByUsername(@RequestParam String username) {
        try {
            UserInfoDTO userInfo = userService.getUserInfoByUsername(username);
            if (userInfo == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 转换为User实体
            User user = new User();
            user.setUserId(userInfo.getUserId());
            user.setUsername(userInfo.getUsername());
            user.setRealName(userInfo.getRealName());
            user.setIdCardNumber(userInfo.getIdCardNumber());
            user.setPhoneNumber(userInfo.getPhoneNumber());
            user.setUserType(userInfo.getUserType());
            user.setActive(userInfo.getActive());
            user.setRegistrationTime(userInfo.getRegistrationTime());
            user.setLastLoginTime(userInfo.getLastLoginTime());
            user.setBalance(userInfo.getBalance());
            
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 检查手机号是否可用
     */
    @GetMapping("/check-phone")
    public ResponseEntity<Boolean> checkPhoneAvailable(@RequestParam String phone) {
        boolean available = userService.isPhoneNumberAvailable(phone);
        return ResponseEntity.ok(available);
    }

    /**
     * 用户充值
     */
    @PostMapping("/{username}/recharge")
    public ResponseEntity<Boolean> recharge(
            @PathVariable String username,
            @RequestParam BigDecimal amount
    ) {
        try {
            UserInfoDTO userInfo = userService.getUserInfoByUsername(username);
            if (userInfo == null) {
                return ResponseEntity.ok(false);
            }

            boolean success = userService.recharge(userInfo.getUserId(), amount);
            return ResponseEntity.ok(success);
        } catch (Exception e) {
            return ResponseEntity.ok(false);
        }
    }

    /**
     * 用户消费
     */
    @PostMapping("/{userId}/deduct")
    public ResponseEntity<Boolean> deductBalance(
            @PathVariable Long userId,
            @RequestParam BigDecimal amount
    ) {
        boolean success = userService.consume(userId, amount);
        return ResponseEntity.ok(success);
    }

    /**
     * 获取用户余额
     */
    @GetMapping("/balance")
    public ResponseEntity<?> getBalance(@RequestParam String userName) {
        try {
            UserInfoDTO userInfo = userService.getUserInfoByUsername(userName);
            if (userInfo == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }
            return ResponseEntity.ok(userInfo.getBalance());
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    /**
     * 支付接口
     */
    @PostMapping("/pay")
    public ResponseEntity<?> pay(@RequestBody Map<String, Object> payRequest) {
        try {
            String userName = (String) payRequest.get("userName");
            Double amount = (Double) payRequest.get("amount");

            if (userName == null || amount == null) {
                return ResponseEntity.badRequest().body("参数错误");
            }

            UserInfoDTO userInfo = userService.getUserInfoByUsername(userName);
            if (userInfo == null) {
                return ResponseEntity.badRequest().body("用户不存在");
            }

            boolean success = userService.consume(userInfo.getUserId(), BigDecimal.valueOf(amount));
            if (success) {
                return ResponseEntity.ok("ok");
            } else {
                return ResponseEntity.badRequest().body("payment_failed: 余额不足");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("payment_failed: " + e.getMessage());
        }
    }

    /**
     * 获取用户个人信息
     */
    @GetMapping("/info")
    public ResponseEntity<UserInfoDTO> getUserInfo(@RequestParam String username) {
        UserInfoDTO userInfo = userService.getUserInfoByUsername(username);
        if (userInfo == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 修改用户名
     */
    @PutMapping("/updateUsername")
    public ResponseEntity<?> updateUsername(@RequestBody Map<String, String> request) {
        try {
            String oldUsername = request.get("oldUsername");
            String newUsername = request.get("newUsername");
            
            if (oldUsername == null || newUsername == null) {
                return ResponseEntity.badRequest().body("参数错误");
            }

            // 检查新用户名是否可用
            boolean available = userService.isUsernameAvailable(newUsername);
            if (!available) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "新用户名已被使用");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查旧用户名是否存在
            UserInfoDTO oldUser = userService.getUserInfoByUsername(oldUsername);
            if (oldUser == null) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "原用户不存在");
                return ResponseEntity.badRequest().body(response);
            }

            // TODO: 实现用户名修改逻辑
            // userService.updateUsername(oldUsername, newUsername);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户名修改成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public ResponseEntity<?> updatePassword(@RequestBody Map<String, String> request) {
        try {
            String username = request.get("username");
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            if (username == null || oldPassword == null || newPassword == null) {
                return ResponseEntity.badRequest().body("参数错误");
            }

            // 验证旧密码
            try {
                LoginRequest loginRequest = new LoginRequest();
                loginRequest.setUsername(username);
                loginRequest.setPassword(oldPassword);
                userService.login(loginRequest);
            } catch (Exception e) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "原密码错误");
                return ResponseEntity.badRequest().body(response);
            }

            // TODO: 实现密码修改逻辑
            // userService.updatePassword(username, oldPassword, newPassword);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "密码修改成功");
            return ResponseEntity.ok(response);
        } catch (RuntimeException e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取用户ID
     */
    @GetMapping("/id")
    public ResponseEntity<Long> getUserIdByUsername(@RequestParam String username) {
        UserInfoDTO userInfo = userService.getUserInfoByUsername(username);
        if (userInfo != null) {
            return ResponseEntity.ok(userInfo.getUserId());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取用户档案
     */
    @GetMapping("/{userId}/profile")
    public ResponseEntity<UserProfileDTO> getUserProfile(@PathVariable Long userId) {
        try {
            UserInfoDTO userInfo = userService.getUserInfo(userId);
            if (userInfo == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 转换为UserProfileDTO
            UserProfileDTO profile = new UserProfileDTO();
            profile.setUserId(userInfo.getUserId());
            profile.setRealName(userInfo.getRealName());
            profile.setUserType(userInfo.getUserType());
            profile.setActive(userInfo.getActive());
            
            return ResponseEntity.ok(profile);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(null);
        }
    }
}
